<script setup>
import { ref } from 'vue'
import { AiAPI } from '@/api/user'
import { marked } from 'marked'

const messages = ref([])
const message = ref('')
const requestCount = ref(0)
const maxRequests = 5 // 最大请求次数
const loading = ref(false) // 防止重复点击
const buttonText = ref('发送') // 按钮文本

// 自动滚动到最新消息
const scrollToBottom = () => {
  const container = document.querySelector('.message_container')
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}

const sendMessage = async () => {
  if (loading.value) return // 防止重复点击
  if (!message.value.trim()) {
    ElMessage.warning('消息不能为空')
    return
  }

  if (requestCount.value >= maxRequests) {
    ElMessage.warning('请求次数已达上限，请稍后再试。')
    return
  }

  // 设置按钮为加载状态
  buttonText.value = '生成中...'

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message.value
  })
  message.value = ''

  try {
    loading.value = true
    const res = await AiAPI({
      messages: messages.value
    })

    // 调用display函数逐字显示AI的回复
    display(res.data.result)
  } catch (error) {
    ElMessage.error('请求失败，请稍后重试')
  } finally {
    loading.value = false
    buttonText.value = '发送' // 恢复按钮文本
    requestCount.value++
  }

  scrollToBottom()

  // 重置请求次数，每小时重置一次
  setTimeout(() => {
    requestCount.value = 0
  }, 3600000)
}

const display = (text) => {
  messages.value.push({
    role: 'assistant',
    content: ''
  })
  let index = 0
  let char

  function type() {
    if (index < text.length) {
      char = text.charAt(index)
      messages.value[messages.value.length - 1].content += char
      index++
      setTimeout(type, 40) // 这里可以调整速度
    } else {
      scrollToBottom() // 自动滚动
    }
  }

  type()
}

// 监听回车键发送消息
const handleKeyUp = (event) => {
  if (event.key === 'Enter') {
    sendMessage()
  }
}
</script>

<template>
  <div class="chat-container">
    <div class="title">欢迎使用AI助手</div>
    <div class="message_container">
      <div v-for="(msg, index) in messages" :key="index" class="message-wrapper" :class="msg.role">
        <div class="one_message" v-html="marked(msg.content, { sanitize: true })"></div>
      </div>
    </div>
    <div class="input-container">
      <el-input v-model="message" placeholder="请在这里输入" @keyup="handleKeyUp" />
      <el-button :disabled="loading" type="primary" @click="sendMessage">{{
        buttonText
      }}</el-button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.title {
  height: 50px;
  line-height: 50px;
  text-align: center;
  color: #3670ee;
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 20px;
}

.message_container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
  height: 400px;
}

.message-wrapper {
  display: flex;
  margin: 10px 0;
  animation: fadeIn 0.5s ease-in-out;
}

.user {
  justify-content: flex-end;
}

.assistant {
  justify-content: flex-start;
}

.one_message {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  word-wrap: break-word; /* 确保消息换行 */
}

.user .one_message {
  background-color: #0084ff;
  color: #fff;
  margin-left: 20px;
}

.assistant .one_message {
  background-color: #fff;
  color: #000;
  margin-right: 20px;
}

.input-container {
  display: flex;
  margin-top: 10px;
}

.input-container el-input {
  flex: 1;
  margin-right: 10px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@media screen and (max-width: 600px) {
  .one_message {
    max-width: 80%;
  }
}
</style>
